#include "StringKey.h"

StringKey::StringKey(const char* key)
	: m_stringKey(new char[strlen(key)]) 
{
		strcpy(m_stringKey, key);
}

void StringKey::SetKey(const char* key) 
{
	if (m_stringKey) {delete[] m_stringKey;} // delete the allocation of the prev stringKey
	m_stringKey = new char[strlen(key)+1]; // allocate space for the new stringKey
	strncpy(m_stringKey, key, strlen(key)); 
	m_stringKey[strlen(key)]='\0'; 
}

int StringKey::Compare(const StringKey& s)
{
	int result = strcmp(m_stringKey, s.GetKey());
	if (result == 0)
		return EQ;
	
	return result > 0 ? GREAT : LESS;
}

// This function reads a stringKey from a file
StringKey* StringKey::Read(ifstream &file)
{
	char curr;
	char string[256];
	int length = 0;

	if (!file.is_open())
		return NULL;

	// for every char entered
	file.get(curr);
	while (file.good() && curr != '\t' && curr != ' ' && curr != '\n')
	{
		string[length] = curr;
		length++;
		file.get(curr);
	}
	string[length] = '\0';

	if (length > 0)
	{
		// allocate new space for the new string
		m_stringKey = new char[length+1];
		strncpy(m_stringKey, string, length+1);
		return this;
	}
	return NULL;
}

// This function reads string key from keyboard
StringKey* StringKey::Read()
{
	char curr;
	char string[256];
	char junk[256];
	int length = 0;
	cout << "Please enter the name of the worker: ";
	// for every char entered
	curr = getc(stdin);
	while (curr != '\t' && curr != ' ' && curr != '\n')
	{
		string[length] = curr;
		length++;
		curr = getc(stdin);
	}
	string[length] = '\0';
	// clears the line from other inputs
	if (curr != '\n') {cin.getline(junk,255);}

	if (length > 0)
	{
		// allocate new space for the new string
		m_stringKey = new char[length+1];
		strncpy(m_stringKey, string, length+1);
		return this;
	}
	return NULL;
}

bool StringKey::operator==(const StringKey& otherKey) const
{
	return strcmp(otherKey.GetKey(), m_stringKey);
}

void StringKey::Print() 
{
	cout << "Key: " << m_stringKey;
}

StringKey::~StringKey(void)
{
	delete m_stringKey;
}
